
// : 'image:${imageUrl}:ave', // imageAve
// : 'image:${imageUrl}:info', // imageInfo

const { IMAGE_QINIU_AVE, IMAGE_QINIU_INFO } = require('../constant/redis');
const Service = require('egg').Service;

class QiniuService extends Service {

    /**
     * 获取七牛CDN图片的平均颜色
     *
     * @param {*} url
     * @returns
     * @memberof QiniuService
     */

    async getImageAve(url) {
        const ctx = this.ctx;
        return new Promise(async (resolve, reject) => {
            const ave = await ctx.service.cache.get([IMAGE_QINIU_AVE, url]);
            if (ave) {
                resolve({ imageAve: ave })
                return;
            }
            const result = await ctx.curl(`${url}?imageAve`, {
                method: 'GET',
                contentType: 'application/json',
                dataType: 'json', // 指定数据格式
                headers: {
                    'Cache-Control': 'no-store'
                },
                timeout: 3000,
            });
            if (result.status === 200) {
                await ctx.service.cache.set([IMAGE_QINIU_AVE, url], result.data, ctx.app.constant.IMAGE_EX * 60 * 60)
                resolve({ imageAve: result.data })
            } else {
                resolve(null)
            }
        })
    }

    /**
     * 获取七牛图片的基本信息
     *
     * @param {*} url
     * @returns
     * @memberof QiniuService
     */
    async getImageInfo(url) {
        const ctx = this.ctx;
        return new Promise(async (resolve, reject) => {
            const info = await ctx.service.cache.get([IMAGE_QINIU_INFO, url]);
            if (info) {
                resolve({ imageInfo: info })
                return;
            }
            const result = await ctx.curl(`${url}?imageInfo`, {
                method: 'GET',
                contentType: 'application/json',
                dataType: 'json', // 指定数据格式
                headers: {
                    'Cache-Control': 'no-store'
                },
                timeout: 3000,
            });
            if (result.status === 200) {
                await ctx.service.cache.set([IMAGE_QINIU_INFO, url], result.data, ctx.app.constant.IMAGE_EX * 60 * 60)
                resolve({ imageInfo: result.data })
            } else {
                resolve(null)
            }
        })
    }
}

module.exports = QiniuService;
